package com.academic_system.service.impl;

import com.academic_system.model.*;
import com.academic_system.mapper.StudentDao;
import com.academic_system.service.StudentService;
import com.academic_system.util.Message;
import com.academic_system.util.Msg;
import com.itextpdf.text.*;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

/**
 * @author 20155887 赵开兰
 * @description 学生业务实现类
 * @project_name StudentImpl
 * @package com.academic_system.service
 
 **/
@Service
//@Transactional(rollbackFor=Exception.class)
public class StudentImpl implements StudentService {
    @Autowired
    private StudentDao studentDao;

    /**
     * @param stu_num
     * @Description 根据Student表中的学生学号查询学生个人信息
     * @author 20155887 赵开兰
     * @methodName queryStudentByStuNum
     * @returnType Message
    
     **/
    //@Cacheable(value = "myCache", key = "'StudentService.queryStudentByStuNum'")
    @Override
    public Message queryStudentByStuNum(int stu_num) {
        System.out.println("*************************************************我是Student*************************************************");
        System.out.println(stu_num);
        StudentInfo student = studentDao.queryStudentByStuNum(stu_num);
        System.out.println(student);
        if (student!=null){
            return Message.success().add("student",student);
        }
        return Message.fail().add("0203","查询失败");
    }

    /**
     * @param stu_num
     * @Description 查询学号是否存在
     * @author 20155887 赵开兰
     * @methodName queryStuNum
     * @returnType int
     
     **/
    @Override
    public Message queryStuNum(int stu_num) {
        Student student=studentDao.queryStuNum(stu_num);
        if (student!=null){
            return Message.success().add("student",student);
        }
        return Message.fail().add("0207","查询失败");
    }

    /**
     * @param student
     * @Description 增加一个学生（学号+密码）
     * @author 20155887 赵开兰
     * @methodName addStudent
     * @returnType Message

     **/
    @Override
    public Message addStudent(Student student) {
        boolean flag = studentDao.addStudent(student,student.getStuInfoId());
        System.out.println("addStudent="+flag);
        if (flag==true){
            return Message.success();
        }
        return Message.fail().add("0204","增加失败");
    }

    /**
     * @param student
     * @Description 修改学生信息表（姓名，性别，身份证，出生年月，民族，电话，籍贯）
     * @author 20155887 赵开兰
     * @methodName updateStudent
     * @returnType Message

     **/
    @Override
    public Message updateStudent(Student student) {
        boolean flag = studentDao.updateStudent(student);
        if (flag==true){
            return Message.success();
        }
        return Message.fail().add("0205","更新失败");
    }

    /**
     * @param stu_num
     * @Description 删除学生信息表【警告！这是真删！无特殊情况不可调用此接口！】
     * @author 20155887 赵开兰
     * @methodName deleteStudent
     * @returnType Message

     **/
    @Override
    public Message deleteStudent(int stu_num) {
        boolean flag = studentDao.deleteStudent(stu_num);
        if (flag==true){
            return Message.success();
        }
        return Message.fail().add("0206","删除失败");
    }

    /**
     * @Description 查询全部学生
     * @author 20155887 赵开兰
     * @methodName queryStudent
     * @returnType Message

     **/
    @Override
    public Message queryStudent() {
        List<Student> studentList=studentDao.queryStudent();
        if (studentList.size()!=0){
            return Message.success().add("studentList",studentList);
        }
        return Message.fail().add("1118","查询失败");
    }

    /**
     * @Description 查询全部年级（除去重复字段）
     * @author 20155887 赵开兰
     * @methodName queryGrade
     * @returnType List

     **/
    @Override
    public List<String> queryGrade() {
        List<String> grade=studentDao.queryGrade();
        return grade;
    }

    /**
     * @Description 跟据学号查学生id
     * @author 20155884 王晓阳
     * @methodName
     * @param
     * @returnType

     **/
    @Override
    public Msg queryStuIdByStuNum(int stuNum){
       Student student= studentDao.queryStuIdByStuNum(stuNum);
        if (student!= null) {
            return Msg.addData(100,"student", student);
        }
        return Msg.fail();
    }

    /**
     * @Description 根据学生id查找学生信息
     * @author 20155884 王晓阳
     * @methodName
     * @param
     * @returnType
     * @create 2018/5/27 23:19
     **/
    public Msg queryStudentByStuId(int stuInfoId){
        Student student= studentDao.queryStudentByStuId(stuInfoId);
        if (student!= null) {
            return Msg.addData(100,"student", student);
        }
        return Msg.fail();
    }

    /**
     * @Description 下载生成学生信息表
     * @author 20155887 赵开兰
     * @methodName download
     * @param
     * @returnType Message

     **/
//    @Override
//    public Message download(String stuNum, String stuName, String stuSex, String stuIdcardNum, String stuBirthday, String stuNation, String stuPoli, String stuPhone, String stuNativeplace, String stuGrade, String cet46Grade, String academyName) throws IOException, DocumentException {
//        System.out.println("-------------------");
//        System.out.println(stuNum);
//        System.out.println(stuName);
//        System.out.println(stuSex);
//        System.out.println(stuIdcardNum);
//        System.out.println(stuBirthday);
//        System.out.println(stuNation);
//        System.out.println(stuPoli);
//        System.out.println(stuPhone);
//        System.out.println(stuNativeplace);
//        System.out.println(stuGrade);
//        System.out.println(cet46Grade);
//        System.out.println(academyName);
//
//        // 模板路径.最终放在服务器下。远程即可访问
//        java.lang.String templatePath = "D:/tj.pdf";
//
//        //保存在指定目录上
//        java.lang.String newPDFPath = "D:/"+stuName+"_天津理工大学学生基本信息表.pdf";
//        //这里应该访问远程的照片，数据表应加一列图片
//        java.lang.String imagePath = "D:/tjut.JPG";
//
//        //图片域的名字
//        java.lang.String fieldName = "img";
//        //
//        PdfReader reader;
//        //输出流
//        FileOutputStream out;
//        //字节数组输出流
//        ByteArrayOutputStream bos;
//
//        //打印
//        PdfStamper stamper;
//        //字体
//        BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
//        try {
//
//
//            out = new FileOutputStream(newPDFPath);// 输出流
//            reader = new PdfReader(templatePath);// 读取pdf模板
//            bos = new ByteArrayOutputStream();
//            stamper = new PdfStamper(reader, bos);
//            AcroFields form = stamper.getAcroFields();
//
//            int pageNo = form.getFieldPositions(fieldName).get(0).page;//获取页面位置
//            Rectangle signRect = form.getFieldPositions(fieldName).get(0).position;//矩形位置
//            float x = signRect.getLeft();
//            float y = signRect.getBottom();
//
//            // 获取操作的页面
//            PdfContentByte under = stamper.getOverContent(pageNo);
//
//            // 添加二维码
//
//            String myString = "Your basic information: stuNum="+stuNum+",grade="+stuGrade+",stuIdcardNum="+stuIdcardNum+",stuBirthday="+stuBirthday;
//            //生成二维码
//            BarcodeQRCode qrcode = new BarcodeQRCode(myString.trim(), 1, 1, null);
//            Image qrcodeImage = qrcode.getImage();
//            qrcodeImage.setAbsolutePosition(x,y);//设置绝对位置
//            qrcodeImage.scalePercent(300);
//
//
//            //image.setAbsolutePosition(x, y);
//            under.addImage(qrcodeImage);
//
//            //设置表单域的内容
//            long dateNow=System.currentTimeMillis();
//            String sR=Long.toString(dateNow);
//
//            form.setFieldProperty("Barcode", "textfont", baseFont, null);
//            form.setField("Barcode","流水号："+sR);
//            form.setField("stuNum",stuNum);
//            form.setFieldProperty("stuName", "textfont", baseFont, null);
//            form.setField("stuName",stuName);
//            form.setFieldProperty("stuSex", "textfont", baseFont, null);
//            form.setField("stuSex", stuSex);
//            form.setFieldProperty("academyName", "textfont", baseFont, null);
//            form.setField("academyName",academyName);
//            form.setField("stuGrade",stuGrade);
//            form.setFieldProperty("stuNation", "textfont", baseFont, null);
//            form.setField("stuNation", stuNation);
//            form.setFieldProperty("stuNativeplace", "textfont", baseFont, null);
//            form.setField("stuNativeplace", stuNativeplace);
//            form.setFieldProperty("stuPoli", "textfont", baseFont, null);
//            form.setField("stuPoli",stuPoli);
//            form.setField("stuBirthday",stuBirthday);
//            form.setField("cet46Grade", cet46Grade);
//            form.setField("stuIdcardNum",stuIdcardNum);
//            form.setField("stuPhone",stuPhone);
////
////            // 如果为false那么生成的PDF文件还能编辑，一定要设为true
//            stamper.setFormFlattening(true);
//            stamper.close();
//            Document doc = new Document();
//
//
//            PdfCopy copy = new PdfCopy(doc, out);
//            doc.open();
//
//            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
//
//
//
//            copy.addPage(importPage);
//            doc.close();
//            reader.close();
//
//
//        } catch (IOException e) {
//            System.out.println(1);
//        } catch (DocumentException e) {
//            System.out.println(2);
//        }
//        return Message.success();
//    }

//    @Override
//    public Message sendMessage(String phone, String stuNum, String stuName, String stuSex, String stuIdcardNum, String stuBirthday, String stuNation, String stuPoli, String stuPhone, String stuNativeplace, String stuGrade, String cet46Grade, String academyName) throws IOException {
//       //客户端
//        HttpClient client = new HttpClient();
//        //post方法请求地址
//        PostMethod post = new PostMethod("http://utf8.sms.webchinese.cn/");
//        post.addRequestHeader("Content-Type",
//                "application/x-www-form-urlencoded;charset=utf-8");// 在头文件中设置转码
//        //发送的内容
//        NameValuePair[] data = { new NameValuePair("Uid", "wshan0117"),//用户名
//                new NameValuePair("Key", "d41d8cd98f00b204e980"),//密钥
//                new NameValuePair("smsMob", phone),//发送的手机号
//                new NameValuePair("smsText", stuName+"同学接收：同学你好！你的基本信息如下：学号："+stuNum+",性别："+stuSex+",身份证号："+stuIdcardNum+",出生年月："+stuBirthday+",民族："+stuNation+"，政治面貌："+stuPoli+"，联系方式："+stuPhone+",籍贯："+stuNativeplace+",年级："+stuGrade+",四六级成绩："+cet46Grade+",学院："+academyName) };
//       //设置请求内容
//        post.setRequestBody(data);
//
//        //客户端执行post请求
//        client.executeMethod(post);
//        //获取响应头文件
//        org.apache.commons.httpclient.Header[] headers = post.getResponseHeaders();
//        //状态码
//        int statusCode = post.getStatusCode();
//        System.out.println("statusCode:" + statusCode);
//        for (Header h : headers) {
//            System.out.println(h.toString());
//        }
//        //响应
//        String result = new String(post.getResponseBodyAsString().getBytes(
//                "utf-8"));
//        System.out.println(result);
//
//        //释放链接
//        post.releaseConnection();
//        return Message.success();
//    }

    /**
     * @param
     * @Description 查找所有学生id， 学号，姓名
     * @author 20155884 王晓阳
     * @methodName
     * @returnType

     **/
    public List<MarkCondition> queryAllStudent() {
        List<MarkCondition> studentList = studentDao.queryAllStudent();
        return studentList;
    }

    @Override
    public boolean addProjet(Project project) {

        int count = studentDao.insertProject(project);
        return false;
    }

    @Override
    public Student queryDisNameAndPwd(String name, String password) {

        return studentDao.queryDisNameAndPwd(name,password);
    }

    @Override
    public List<Project> findAllProject() {

        return studentDao.findAllProject();
    }

    @Override
    public List<StuProject> findAllStuProject() {

        return studentDao.findAllStuProject();
    }

    @Override
    public List<StuProject> findMyProject(int stuId) {
        // TODO Auto-generated method stub
        return studentDao.findMyProject(stuId);
    }

    @Override
    public boolean changeMyProject(StuProject stuProject) {
        // TODO Auto-generated method stub
        return studentDao.changeMyProject(stuProject);
    }

    @Override
    public boolean removeMyProject(StuProject stuProject) {
        // TODO Auto-generated method stub
        return studentDao.removeMyProject(stuProject);
    }

    public boolean queryStudentByNumAndPwd(String name, String password) {
        int count = studentDao.queryStudentByNumAndPwd(name,password);
        boolean flag = false;
        if(count>0) {
            flag = true;
        }
        return flag;
    }

    @Override
    public boolean queryTeacherByNumAndPwd(String name, String password) {
        int count = studentDao.queryTeacherByNumAndPwd(name,password);
        boolean flag = false;
        if(count>0) {
            flag = true;
        }
        return flag;
    }
}
